﻿package com.bbx.taxi.client.Activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;

import com.bbx.androidapi.util.ToastUtil;
import com.bbx.taxi.official.R;
import com.bbx.taxi.client.Activity.Base.BaseBBXActivity;
import com.bbx.taxi.client.Bean.Value;
import com.bbx.taxi.client.Bean.Attribute.MainAttribute;
import com.bbx.taxi.client.Bean.Extra.ContactPersonMsg;
import com.bbx.taxi.client.DB.ContactsDB;
import com.bbx.taxi.client.DB.Util.DBcolumns;
import com.bbx.taxi.client.Util.Phone;
import com.bbx.taxi.client.Util.StringFilter;
import com.bbx.taxi.client.widget.MaxByteLengthEditText;
import com.example.mylistview.pullListView.PullToRefreshLayout;
import com.example.mylistview.pullListView.PullToRefreshLayout.OnRefreshListener;
import com.example.mylistview.pullListView.PullableListView;
import com.example.mylistview.pullListView.PullableListView.OnLoadListener;
import com.example.mylistview.swipemenu.MyListView;
import com.example.mylistview.swipemenu.MyListView.OnMenuItemClickListener;
import com.example.mylistview.swipemenu.MyListView.OnSwipeListener;
import com.example.mylistview.swipemenu.SwipeMenu;
import com.example.mylistview.swipemenu.SwipeMenuCreator;
import com.example.mylistview.swipemenu.SwipeMenuItem;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 联系人
 */
public class ContactPersonActivity extends BaseBBXActivity implements OnFocusChangeListener{
	@InjectView(R.id.layout_addresslist)
	LinearLayout layout_addresslist;
	@InjectView(R.id.telephone)
	EditText telephone;
	@InjectView(R.id.contactperson)
	MaxByteLengthEditText contactperson;
	@InjectView(R.id.iv_contact_del)
	ImageView iv_contact_del;
	@InjectView(R.id.iv_tel_del)
	ImageView iv_tel_del;
	@InjectView(R.id.cb_need_sms)
	CheckBox cb_need_sms;
	@InjectView(R.id.btn_confirm)
	Button btn_confirm;
	private String username, usernumber;
	private ContactsDB db_contacts;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.contactperson);
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void initView() {
		setTitle(true, "联系人", -1, "历史");
		layout_addresslist.setOnClickListener(this);
		iv_contact_del.setOnClickListener(this);
		btn_confirm.setOnClickListener(this);
		iv_tel_del.setOnClickListener(this);
		 /////////////////////////////
			Intent intent = getIntent();
			if (intent.getExtras() != null) {
				username = intent.getExtras().getString(
						ContactPersonMsg.extra_contact_name);
				usernumber = intent.getExtras().getString(
						ContactPersonMsg.extra_contact_phone);
			}
			telephone.setOnFocusChangeListener(this);
			contactperson.setOnFocusChangeListener(this);
			contactperson.setText(username);
			contactperson.setSelection(contactperson.getText().length());
			telephone.setText(usernumber);
			telephone.setSelection(telephone.getText().length());
			contactperson.addTextChangedListener(new TextWatcher() {
				@Override
				public void onTextChanged(CharSequence arg0, int arg1, int arg2,
						int arg3) {
				}

				@Override
				public void beforeTextChanged(CharSequence arg0, int arg1,
						int arg2, int arg3) {
				}

				@Override
				public void afterTextChanged(Editable s) {
					if (!s.toString().isEmpty()) {
						iv_contact_del.setVisibility(View.VISIBLE);
					} else {
						iv_contact_del.setVisibility(View.GONE);
					}
				}
			});
			telephone.addTextChangedListener(new TextWatcher() {
				@Override
				public void onTextChanged(CharSequence arg0, int arg1, int arg2,
						int arg3) {
				}

				@Override
				public void beforeTextChanged(CharSequence arg0, int arg1,
						int arg2, int arg3) {
				}

				@Override
				public void afterTextChanged(Editable s) {
					if (!s.toString().isEmpty()) {
						iv_tel_del.setVisibility(View.VISIBLE);
					} else {
						iv_tel_del.setVisibility(View.GONE);
					}
				}
			});
	}

	@Override
	protected void initData() {
		db_contacts=new ContactsDB(context);

	}

	@Override
	protected void desotryItems() {
		// TODO Auto-generated method stub

	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_right:
			startActivityForResult(new Intent(this,HistoryContactsActivity.class), requestCode);
			break;
		case R.id.btn_confirm:
			if (contactperson.getText().toString().equals("")||contactperson.getText().toString().replaceAll(" ", "").equals("")) {
				ToastUtil.showToast(context, R.string.name_no_empty);
				return;
			}
			if (telephone.getText().toString().equals("")) {
				ToastUtil.showToast(context, R.string.tel_no_empty);
				return;
			}
			onWriteDB(contactperson.getText().toString(), telephone.getText()
					.toString(), "0");
			Bundle bundle = new Bundle();
			bundle.putString("name", contactperson.getText().toString());
			bundle.putString("telephone", telephone.getText().toString());
			Intent intent = new Intent();
			intent.putExtras(bundle);
			setResult(MainAttribute.REQUEST_CODE_PERSON, intent);
			onfinish();
			break;
		case R.id.layout_addresslist:
			startActivityForResult(new Intent(Intent.ACTION_PICK,
					ContactsContract.Contacts.CONTENT_URI),requestCode);
			break;
		// case R.id.clearall:
		// list.clear();
		// mCommonContactAdapter.notifyDataSetChanged();
		// Toast.makeText(ContactPersonActivity.this, "删除成功",
		// Toast.LENGTH_SHORT).show();
		// break;
		case R.id.iv_contact_del:
			contactperson.setText("");
			break;
		case R.id.iv_tel_del:
			telephone.setText("");
			break;
		default:
			super.onClick(v);
			break;
		}
	}
	/**
	 * 写入数据库
	 */
	public void onWriteDB(String name, String tel, String collection) {
		db_contacts.onWrite(name, tel, collection);
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			try {
				ContentResolver reContentResolverol = getContentResolver();
				Uri contactData = data.getData();
				@SuppressWarnings("deprecation")
				Cursor cursor = managedQuery(contactData, null, null, null,
						null);
				cursor.moveToFirst();
				username = cursor
						.getString(cursor
								.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
				String contactId = cursor.getString(cursor
						.getColumnIndex(ContactsContract.Contacts._ID));
				Cursor phone = reContentResolverol.query(
						ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
						null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID
								+ " = " + contactId, null, null);
				while (phone.moveToNext()) {
					if (phone
							.getString(
									phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
							.substring(0, 2).equals("86")) {
						usernumber = phone
								.getString(
										phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
								.substring(
										2,
										phone.getString(
												phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
												.length()).trim();
					} else {
						usernumber = phone
								.getString(
										phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
								.replace("+86", "").trim();
					}
					telephone.setText(StringFilter.onStringToNumber(usernumber));
					contactperson.setText(username);
					contactperson.setSelection(contactperson.length());

				}
			} catch (Exception e) {
				Toast.makeText(context, "帮邦行已被禁止权限，读取系统通讯。可以在手机管家-权限管理重新授权",
						Toast.LENGTH_SHORT).show();

			}
		}else if(this.requestCode==requestCode&&this.requestCode==resultCode){
			username=data.getStringExtra(ContactPersonMsg.extra_contact_name);
			usernumber=data.getStringExtra(ContactPersonMsg.extra_contact_phone);
			telephone.setText(StringFilter.onStringToNumber(usernumber));
			contactperson.setText(username);
			contactperson.setSelection(contactperson.length());
		}
	}

	
	@Override
	public void onFocusChange(View v, boolean focus) {
		if (v == contactperson) {

			if (focus) {
				if (contactperson.length() == 0) {
					iv_contact_del.setVisibility(View.GONE);
				} else {
					iv_contact_del.setVisibility(View.VISIBLE);
				}
			} else {
				iv_contact_del.setVisibility(View.GONE);
			}
		} else if (v == telephone) {
			iv_tel_del.setVisibility(View.VISIBLE);
			if (focus) {
				if (telephone.length() == 0) {
					iv_tel_del.setVisibility(View.GONE);
				} else {
					iv_tel_del.setVisibility(View.VISIBLE);
				}
			} else {
				iv_tel_del.setVisibility(View.GONE);
			}
		}

	}
}
